<template>
  <div class="pages specificationtype" id="app">
    <div class="pageLevel" v-if="!sub">
      <div class="infon_text">
        <span class="infon_shu"></span>
        <el-button type="primary" @click="specificationModel()" size="mini">添加规格型号</el-button>
        <!-- v-if="setRole('新增')" -->
      </div>
      <div style="padding:10px;">
        <el-table :data="gridData" stripe border ref="multipleTable" tooltip-effect="dark" style="width: 100%;margin:20px auto;">
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column prop="paramName" label="规格名称" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.paramName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="paramValue" label="规格值" align="center">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.value" :key="index" style="display:inline-block">
                <span>{{item.paramValue}}<span v-if="scope.row.value.length>0">&nbsp;&nbsp;</span></span>
              </div>

            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.remark}}</span>

            </template>
          </el-table-column>
          <el-table-column prop="name" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button size="small" @click="specificationEdit(scope.row)" type="text" class="addDetail">修改</el-button>
              <el-button size="small" @click="specificationDelece(scope.$index, scope.row)" type="text" class="addDetail">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="small" type="primary" class="topage" @click="toPage">确定</el-button>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalItems">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="添加规格型号" center class="addshopname" :visible.sync="dialogTableVisible1" :closeOnClickModal='false' :closeOnPressEscape='false'>
      <i class="el-icon-close icon" @click="dialogTableVisible1=false"></i>
      <el-form :model="form" :rules="rules1" ref="form" label-width="100px" class="demo-form">
        <div class="affix">
          <div class="letter">
            <el-form-item label="字段名称:" prop="name">
              <el-input v-model="form.name" maxlength="16" size="small"></el-input>
              <span class="span1">(最多16字)</span>
            </el-form-item>
          </div>
          <div class="append" id="appends">
            <!-- 字段值 -->
            <el-form-item label="字段值:" prop="dynamicTags">
              <ul>
                <el-tag :close="asasa()" v-for="(tag,index) in dynamicTags" :key="index" :closable='true' :disable-transitions="false" @close="handleClose(tag)">
                  {{tag.paramValue}}
                </el-tag>
                <el-input class="input-new-tag" maxlength="10" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                </el-input>
                <el-button v-show="keep" v-else class="button-new-tag" size="small" @click="showInput">新增</el-button>
              </ul>
            </el-form-item>
          </div>
        </div>
        <div>
          <el-form-item label="备注:" prop="remark">
            <textarea maxlength="20" v-model="form.remark" name="" id="" cols="10" rows="5" style="width:220px;resize:none;border-radius:5px;"></textarea>
            <span class="span1">(最多20字)</span>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel" size="small">取 消</el-button>
        <el-button type="primary" @click="submitFormzd('form')" size="small">保 存</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import util from "@/util";
import { mapState } from "vuex";
import {
  getGoodsParameterListByPage,
  saveGoodsParameter,
  updateGoodsParameter,
  isConnectGoodsShop
} from "@/api";
export default {
  computed: mapState(["sub", "power","merchantId"]),
  data() {
    return {
      formInline: {
        user: "",
        region: ""
      }, //规格型号的值
      form: {
        name: "", //规格名称
        remark: "" //备注
      }, //弹窗里面的规格
      added: [],
      dynamicTags: [], //字段值
      dialogTableVisible1: false,
      inputVisible: false,
      inputValue: "",
      keep: true, //弹窗里面的新增显示隐藏
      gridData: [], //列表中的数组
      // 分页开始
      total: 0,
      pageSize: 20,
      totalItems: 0,
      currentPage: 1,
      id: "", //修改时的id
      rules1: {}
    };
  },
  mounted() {
    this.specificationList(this.pageSize, 1);
  },
  methods: {
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    //   添加规格型号
    specificationModel() {
      if (this.dynamicTags.length == 10) {
        this.keep = true;
      }
      this.dialogTableVisible1 = true;
      this.dynamicTags = [];
      this.form.name = "";
      this.form.remark = "";
    },
    //弹窗中的取消按钮
    cancel() {
      this.dialogTableVisible1 = false;
    },
    // 弹窗中的确定按钮
    submitFormzd(formName) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      setTimeout(() => {
        loading.close();
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.sure();
          } else {
            return false;
          }
        });
      }, 700);
    },
    // 新增接口
    sure() {
      console.log(this.dynamicTags);
      let tagArray = [];
      this.dynamicTags.forEach(element => {
        tagArray.push(element.paramValue);
      });
      let a = {
        paramName: this.form.name.toString(),
        paramValue: tagArray.toString(),
        remark: this.form.remark.toString()
      };
      this.added.push(a);
      if (this.form.name == "") {
        this.$message({
          type: "error",
          message: "字段名不能为空"
        });
      }
      for (let k = 0; k < this.added.length; k++) {
        var bb = this.added[k].paramValue.split(",");
        for (let q = 0; q < bb.length; q++) {
          if (bb[q] == " " || bb[q] == "") {
            this.added = [];
            this.$message({
              type: "error",
              message: "字段值不能为空"
            });
            return false;
          }
        }
      }
      if (this.id != "") {
        updateGoodsParameter({
          paramName: this.form.name.toString(),
          paramValue: tagArray.toString(),
          remark: this.form.remark.toString(),
          id: this.id,
          shopId:this.merchantId
        }).then(res => {
          if (res.code == "200") {
            this.dialogTableVisible1 = false;
            this.specificationList(this.pageSize, 1);
            this.id = "";
            this.$message({
              type: "success",
              message: "修改成功"
            });
          }
        });
      } else {
        saveGoodsParameter({
          paramName: this.form.name.toString(),
          paramValue: tagArray.toString(),
          remark: this.form.remark.toString(),
          shopId:this.merchantId
        }).then(res => {
          if (res.code == "200") {
            this.dialogTableVisible1 = false;
            this.specificationList(this.pageSize, 1);
            this.$message({
              type: "success",
              message: "新增成功"
            });
          }
        });
      }
    },
    // 《新增字段》
    handleClose(tag) {
      if (tag.id != "") {
        isConnectGoodsShop({
          goodsParameterDetailId: tag.id
        }).then(res => {
          if (res.code == 200) {
            if (res.data.flag == true) {
              this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
            } else {
              this.$message({
                type: "error",
                message: "商品规格型号与商户商品关联不能修改"
              });
            }
          }
        });
      } else {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      }
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        let obj = {
          id: "",
          paramValue: inputValue
        };
        this.dynamicTags.push(obj);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    asasa() {
      if (this.dynamicTags.length == 10) {
        this.keep = false;
      } else {
        this.keep = true;
      }
    },
    // 列表数据
    specificationList(pageSize, pageNum) {
      getGoodsParameterListByPage({
        pageSize: pageSize,
        pageNo: pageNum,
        shopId:this.merchantId
      }).then(res => {
        if (res.code == 200) {
          this.gridData = res.data.list;
          this.totalItems = res.data.total;
        }
      });
    },
    // 修改
    specificationEdit(rows) {
      this.dialogTableVisible1 = true;
      this.form.name = rows.paramName;
      let arr = [];
      for (var i = 0; i < rows.value.length; i++) {
        let obj = {
          paramValue: rows.value[i].paramValue,
          id: rows.value[i].id
        };
        arr.push(obj);
      }
      this.dynamicTags = arr;
      this.form.remark = rows.remark;
      this.id = rows.id;
    },
    specificationDelece(index, rows) {
      this.$confirm("确定要删除吗?", "提示", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      }).then(() => {
        updateGoodsParameter({
          id: rows.id,
          status: "0"
        }).then(res => {
          if (res.code == "200") {
            this.specificationList(20, 1);
            this.$message({
              type: "success",
              message: res.msg
            });
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        });
      });
    },
    // 分页
    toPage() {
      this.specificationList(this.pageSize, this.currentPage);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.specificationList(this.pageSize, this.currentPage);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.specificationList(this.pageSize, this.currentPage);
    }
  }
};
</script>
<style lang="" scoped>
#app {
  text-align: left;
}
.infon_text {
  margin-top: 20px;
  margin-left: 50px;
}
.user {
  margin-top: 20px;
}
.append {
  margin-top: 10px;
  position: relative;
}
.append ul {
  margin-left: -40px;
  margin-top: 0;
}
.append ul span {
  margin-bottom: 10px;
  margin-left: 6px;
}
.append ul li input {
  width: 100px;
  line-height: 24px;
  text-indent: 6px;
  color: #ccc;
}
.span1 {
  color: #333;
  font-size: 13px;
}
</style>
